<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 商品配件类
 * @package  htdocs
 * @subpackage  quanliadmin
 * @author   create by allen.qiang
 * @version 1.0
 */

class goodsFittings {

    private $dbca;

    public function __construct( $dbca ) {
        $this->dbca = $dbca;
    }


    /**
     * 删除配件
     *
     */
    public function deleteFittings ( $arg_array ) {

        $delete_array = explode('_', $arg_array['delete_str']);
        try {
            $this->dbca->beginTransaction();

            //循环删除规格组
            foreach( $delete_array as &$g_l ) {

                $sql_del_specgroup_info = 'DELETE FROM goods_fittings WHERE fitID = ? ';

                $this->dbca->stmt_query($sql_del_specgroup_info,'i',$g_l);

            }
            $this->dbca->commit();

            return array( 'code' => 200, 'message' => '商品配件删除成功' );
        } catch (Exception $e) {
            $this->dbca->rollBack();
            error_log($e->getTraceAsString());
            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
    }

    /**
     * 商品配件列表
     */
    public function goodsSeachFittings ( &$arg_array ) {
        error_log(var_export($arg_array,true));
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //规格ID
        if (isset($arg_array['fitID']) && is_numeric($arg_array['fitID'])) {
            $sql .= ' AND fitID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['fitID'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        $search_sql = 'SELECT fitName,fitUnit,sortOrder,fitID,image FROM goods_fittings ' . $sql;
        $temp_count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
        $image = substr($temp_count_array[0]->image, 27);
        $count_array = array('fitName'=>$temp_count_array[0]->fitName,
            'fitUnit'=>$temp_count_array[0]->fitUnit,
            'sortOrder'=>$temp_count_array[0]->sortOrder,
            'fitID'=>$temp_count_array[0]->fitID,
            'image'=>!empty($temp_count_array[0]->image) ? G_IMAGE_URL  . $image : ''
        );
        return $count_array;
    }


    /**
     * 保存和更新配件
     */
    public function saveGoodsFittings ( $arg_array ) {

        $goods_spec_group = new entity('goods_fittings');
        $goods_spec_group->fitID = $arg_array['fitID'];
        $ctime = date("Y-m-d H:i:s");

        if(!$this->dbca->fetch($goods_spec_group)){   //添加
            $goods_spec_group->createTime           = $ctime;
            //商品配件名称 序号不能重复
            $fittingsArray = $this->dbca->stmt_query('SELECT fitName,sortOrder FROM goods_fittings');
        }else{
            $fittingsArray = $this->dbca->stmt_query('SELECT fitName,sortOrder FROM goods_fittings WHERE fitID != ?','i',$arg_array['fitID']);
        }

        //商品配件名称 序号不能重复
        $msg = '';
        if($fittingsArray){
            foreach ($fittingsArray as $v) {
                if ($v->sortOrder == $arg_array['sortOrder']) {
                    $msg.= '排序序号已存在<br />';
                }
                if ($v->fitName == $arg_array['fitName']) {
                    $msg.= '配件名称已存在<br />';
                }
            }
        }

        if (!empty($msg)) {
           return array('code'=>400,'message'=>$msg);
        }

        //截取图片名称
        if(!empty($arg_array['hidImg'])){
            $imageName = substr($arg_array['hidImg'], -23);

        }else{
            $imageName = "";
        }
        $goods_spec_group->timeStamp            = $ctime;
        $goods_spec_group->creator              = $arg_array['creator'];
        $goods_spec_group->fitName              = $arg_array['fitName'];
        $goods_spec_group->fitUnit              = $arg_array['fitUnit'];
        $goods_spec_group->sortOrder            = $arg_array['sortOrder'];
        $goods_spec_group->image               = !empty($arg_array['hidImg']) ? '/quanliadmin/docroot/images/system/fittings/'.date('Ymd').'/'.$imageName : $imageName;
        $goods_spec_group->useFlg               = $arg_array['useFlg'];

        $result = $this->dbca->save($goods_spec_group);
        if($result){
            if($arg_array['fitID']){
                return array('code' => 200, 'message' => '商品配件修改成功', 'fitID' => $arg_array['fitID'], 'sortOrder' => $arg_array['sortOrder']+1);
            }else{
                return array('code' => 200, 'message' => '商品配件保存成功', 'fitID' => '', 'sortOrder' => $arg_array['sortOrder']+1);
            }
        }else{
            return array('code' => 400, 'message' => '保存失败，请重试', 'fitID' => $arg_array['fitID'], 'sortOrder' => $arg_array['sortOrder']+1);

        }

    }

    /**
     * 规格最大序号
     */
    public function maxSortOrder(){
        $sortOrder = &$this->dbca->stmt_query('SELECT MAX(sortOrder) sort FROM goods_fittings');
        if (is_null($sortOrder[0]->sort)) {
            return 1;
        } else {
            return $sortOrder[0]->sort + 1;
        }
    }

    /**
     * 商品配件列表
     */
    public function goodsFittings ( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
        
        //配件ID
        if (isset($arg_array['fitID']) && !empty($arg_array['fitID'])) {
            $sql .= ' AND fitID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['fitID']);
        }

        //配件名称
        if (isset($arg_array['fitName']) && !empty($arg_array['fitName'])) {
            $sql .= ' AND fitName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['fitName']) . '%';
        }

        //使用标志
        if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg']) && in_array($arg_array['useFlg'],array(0,1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_fittings ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询配件信息
            $search_sql = 'SELECT * FROM goods_fittings ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

            	$unitName = '';

            	if ($item->fitUnit == 1) {
            		$unitName = '套';
            	} else if ($item->fitUnit == 2) {
            		$unitName = '份';
            	} else if ($item->fitUnit == 3) {
            		$unitName = '个';
            	} else if ($item->fitUnit == 4) {
            		$unitName = '包';
            	} else if ($item->fitUnit == 5) {
                    $unitName = '支';
                }
            	
                $item_array[] = array(
                    'fitID'	=> $item->fitID,
                    'fitName'	=> $item->fitName,
                    'fitUnit'	=> $item->fitUnit,
                    'unitName'	=> $unitName,
                    'sortOrder'	=> $item->sortOrder,
                    'image'	=> !empty($item->image) ? G_IMAGE_URL  . $item->image : '',
                    'useFlg'	=> $item->useFlg
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 配件的使用和禁用
     */
    public function changeUse($arg_array){

        if (!isset($arg_array['fitID']) || $arg_array['fitID'] == '')
            return array( 'code' => 400, 'message' => '缺少参数' );

        //查询配件是否存在或已经被操作
        $tagGroupInfo = new entity('goods_fittings');
        $tagGroupInfo->fitID = $arg_array['fitID'] ;
        if (!$this->dbca->fetch( $tagGroupInfo ))
            return array( 'code' => 400, 'message' => '配件信息未找到，请核实');

        //检查配件状态是否已经修改
        if($tagGroupInfo->useFlg == $arg_array['useFlg']  && $arg_array['useFlg'] == 1)
            return array( 'code' => 400, 'message' => '配件已启用');

        if($tagGroupInfo->useFlg == $arg_array['useFlg'] && $arg_array['useFlg'] == 0)
            return array( 'code' => 400, 'message' => '配件已禁用');

        //修改状态
        $tagGroupInfo->useFlg = $arg_array['useFlg'] ;
        $this->dbca->save( $tagGroupInfo );

        if ($arg_array['useFlg'] == 1) {
            return array( 'code' => 200, 'message' => '配件启用成功');
        } else {
            return array( 'code' => 200, 'message' => '配件禁用成功');
        }
    }
    
    /**
     * 商品配件映射表
     */
    public function searchGoodsFitsRelation ( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
        
        //配件ID
        if (isset($arg_array['fitID']) && !empty($arg_array['fitID'])) {
            $sql .= ' AND fitID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['fitID']);
        }
        
        //网购号
        if (isset($arg_array['postID']) && !empty($arg_array['postID'])) {
            $sql .= ' AND postID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['postID']);
        }
        
        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_fittings_relation ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询配件信息
            $search_sql = 'SELECT * FROM goods_fittings_relation ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

            	$unitName = '';
            	if ($item->fitUnit == 1) {
            		$unitName = '套';
            	} else if ($item->fitUnit == 2) {
            		$unitName = '份';
            	} else if ($item->fitUnit == 3) {
            		$unitName = '个';
            	} else if ($item->fitUnit == 4) {
            		$unitName = '包';
            	} else if ($item->fitUnit == 5) {
                    $unitName = '支';
                }
            	
                $item_array[] = array(
                    'postID'	=> $item->postID,
                    'fitID'	=> $item->fitID,
                    'fitName'	=> $item->fitName,
                    'fitUnit'	=> $item->fitUnit,
                    'unitName'	=> $unitName,
                    'quantity'	=> $item->quantity,
                    'forsale'	=> $item->forsale,
                    'price'	=> $item->price,
                    'buyNum'	=> 0,
                    //mod by yim.hu WEB-0002 FUN-BK-0009_配送单优化 end
                    //'buyMoney'	=> 0.00,
                    'buyMoney'	=> $item->buyMoney,
                    //mod by yim.hu WEB-0002 FUN-BK-0009_配送单优化 end
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }
}